<template>
    <div class="container">
      <div v-if="loading" class="loading">
         <a-spin tip="正在加载案件信息..."/>
      </div>
      <template v-else>
      <h1>案件基本信息</h1>
      <a-descriptions :column="2">
        <a-descriptions-item label="案件编号">
          {{lawCase.number}}
        </a-descriptions-item>
        <a-descriptions-item label="案件名称">
          {{lawCase.name}}
        </a-descriptions-item>
        <a-descriptions-item label="案件简介">
            {{lawCaseDescribe}}
          <template v-if="lawCase.describe && lawCase.describe.length > 150">
            ...
            <a-button type="link" size="small" @click="isShowDescribe=true">查看</a-button>
          </template>
        </a-descriptions-item>
      </a-descriptions>

       <a-divider></a-divider>

      <a-row type="flex" justify="space-between">
        <a-col> <h1>案件任务</h1> </a-col>
        <template  v-if="!lawCase.isRead">
          <a-col span="2">
          </a-col>
          <a-col > 
            <a-button-group>
            <a-button  v-if="!beginSort" type="primary" size="large" @click="beginSort = true">调整顺序 </a-button>
            <a-button  v-else type="primary" size="large" @click="finshSort">完成调整</a-button>
            <a-button  type="primary" size="large" @click="isShowCreateStageModal = true">新建阶段 </a-button>
            </a-button-group>
          </a-col>
         </template>
      </a-row>

      <a-collapse :accordion="false">
        <template v-if="!beginSort">
           
          <a-collapse-panel v-for="(stage,i) in lawCase.stages"  :key="stage.id+'_'" >
            <template slot="header">
              <span style="margin-right: 10px;">{{(i+1) + ' ' + stage.name}}</span>
              <span style="color: #999">{{stage.tasks.length}}个任务</span>
            </template>

            <template slot="extra" v-if="!lawCase.isRead">
                <a-button-group>
                  <!-- 创建任务 -->
                  <a-button type="primary" size="small" icon="plus-circle" @click.stop="showCreateTaskItemModel(i)" />
                  <!-- 删除任务 -->
                  <a-button type="primary" size="small" icon="minus-circle" @click.stop="showDeleteTaskItemConfirm(i)" />
                  <!-- 删除阶段 -->
                  <a-button type="primary" size="small" icon="delete" @click.stop="showDeleteStageConfirm(stage.id,stage.name)"/>
              </a-button-group>
            </template>
            
            <!-- v-model="tasksGroup[i]" -->
             <a-checkbox-group v-if="stage.tasks"  style="width: 100%">
              <a-list :data-source="stage.tasks" size="small" :split="true" :loading="false">
                  <!-- 任务列表 -->
                  <a-list-item slot="renderItem" slot-scope="task, j" :key="task.id" v-dragging="{ item: task, list: stage.tasks, group: 'task'+i }" @mouseenter="taskShare = task.id" @mouseleave="taskShare = ''">
                    <a-row type="flex" style="width: 100%" justify="start" >
                      <a-col span="1" style="text-align : center">
                        <a-checkbox v-if="!lawCase.isRead" :value="task.id" @change="(e)=>change(e,i)"></a-checkbox>
                      </a-col>
                      <a-col span="20">
                        <span @click="showUpdateTaskItemModel(i,j)" style="margin-left : 5px; cursor: pointer;">{{ " "+(i+1) +"." + (j+1) + " " + task.name }}</span>
                      </a-col>
                       <a-col span="1" style="text-align : center">
                             <a-icon v-show="taskShare == task.id" type="share-alt" @click="share(task.id)" />
                       </a-col>

                      <a-col span="1" style="text-align : center">
                        <a-icon type="bars" /><span> {{task.checkItems ? task.checkItems.length : 0}}</span>
                      </a-col>
                      <a-col span="1" style="text-align : center">
                        <a-icon type="link" /><span> {{task.files ? task.files.length : 0}}</span>  
                      </a-col>
                    </a-row>
                  </a-list-item>
              </a-list>
            </a-checkbox-group>
          </a-collapse-panel>
      </template>
      <template v-else>
          <a-collapse-panel disabled   v-for="(stage,i) in lawCase.stages" :key="stage.id" v-dragging="{ item: stage, list: lawCase.stages, group: 'stage' }">
            <template slot="header">
              <span style="margin-right: 10px;">{{(i+1) + ' ' + stage.name}}</span>
              <span style="color: #999">{{stage.tasks.length}}个任务</span>
            </template>

            <template slot="extra" v-if="!lawCase.isRead">
                <a-button-group>
                  <a-button type="primary" size="small" icon="plus-circle" @click.stop="showCreateTaskItemModel(i)" />
                  <a-button type="primary" size="small" icon="minus-circle" @click.stop="showDeleteTaskItemConfirm(i)" />
                  <a-button type="primary" size="small" icon="delete" @click.stop="showDeleteStageConfirm(stage.id,stage.name)"/>
              </a-button-group>
            </template>
   
          </a-collapse-panel>
        </template>
       </a-collapse>

    <a-modal v-model="isShowDescribe" title="案件简介" @ok="isShowDescribe=false" :footer="null">
      <p style="text-indent : 2em">
       {{lawCase.describe}}
      </p>
    </a-modal>

    <a-modal v-if="!lawCase.isRead" v-model="isShowCreateStageModal" title="添加阶段" 
                @ok="createStage" okText="确定" 
                @cancel="cancelCreateStage" cancelText="取消" :confirmLoading="createStageLoadding">
      <a-input v-model="stageName" placeholder="阶段名称" />
    </a-modal>

    <a-modal v-if="!lawCase.isRead" v-model="isShowCreateTaskModal" title="新建任务" 
                  @ok="createTask" okText="确定" 
                  @cancel="cancelCreateTask" cancelText="取消" :confirmLoading="createTaskLoadding">
       <a-input v-model="taskName" placeholder="任务名称" />
    </a-modal>

     <a-modal v-if="isShowUpdateTaskModeal" v-model="isShowUpdateTaskModeal" 
     :title="updateTaskModealTitle" :dialogStyle="{'margin-top' : '-60px'}" 
     okText="确定" cancelText="取消"
     @ok="updateTask"
     @cancel="cancelUpdateTask">
       <div style="height: 500px;overflow: auto; padding: 0px 15px">
       <h4>{{ " "+(curStageIndex + 1) + "." + (curTaskIndex + 1) + " " + taskForm.name }}</h4>
       <a-form-model>
         <a-form-model-item label="说明">
          <a-textarea
            :auto-size="{ minRows: 2, maxRows: 4 }"
            :disabled="lawCase.isRead"
            v-model="taskForm.describe"
          />
        </a-form-model-item>

        <a-form-model-item>
          <a-spin tip="正在上传" :spinning="uploading">
          <a-upload-dragger
            :multiple="false"
            :disabled="lawCase.isRead"
            :remove="fileRemove"
            :showUploadList="false"
            :customRequest="customRequest"
            @change="uploadChange"
          >
            <p class="ant-upload-drag-icon">
              <a-icon type="inbox" />
            </p>
            <p class="ant-upload-text">
              点击或者拖拽文件到这个区域来上传具体事项文件
            </p>
          </a-upload-dragger>
          <div v-for="file in taskForm.files" :key="file.id" style="color:#40a9ff; cursor: pointer;display:flex;align-items:center;" >
            <a-icon type="link" />
            <span  @click="gotoPdfOCR(file.id)"> {{file.fileName}}</span>
             <a-popconfirm title="确定要删除吗？" placement="topRight" ok-text="确定" cancel-text="取消" @confirm="delFile(file.id)">
           <a-icon type="delete" style="color:red;margin-left:auto" />
           </a-popconfirm>
          </div>
          </a-spin>
        </a-form-model-item>

        <a-form-model-item>
          <a-row type="flex" justify="space-between">
          <a-col>
          <span style="font-size: 16px; font-weight: 700; margin-right: 10px">检查项</span>
          <span style="color: #999; font-size:12px"> 当前进度: {{taskFormCheckItemsIsDone}} / {{taskForm.checkItems.length}}</span>
          </a-col>
          <a-col>
              <a-button v-if="!lawCase.isRead" type="primary" size="small" @click="showCreateCheckItemModal">新增</a-button>
          </a-col>
        </a-row>
          <a-list :data-source="taskForm.checkItems" size="small" :split="true">
            <a-list-item slot="renderItem" slot-scope="checkItem,k" style="widht:100%">
                <a-row type="flex" style="width: 100%">
                  <a-col :span="22">
                    <a-checkbox :disabled="lawCase.isRead" v-model="checkItem.isDone">{{ checkItem.name }}</a-checkbox>
                  </a-col>
                  <a-col :span="2" style="text-align: center">
                    <a-popconfirm title="确定要删除吗？" placement="topRight" ok-text="确定" cancel-text="取消" @confirm="taskForm.checkItems.splice(k,1)">
                      <a-button v-if="!lawCase.isRead" type="primary"  size="small" icon="delete" />
                    </a-popconfirm>
                  </a-col>
                </a-row>
              </a-list-item>
          </a-list>
       
        </a-form-model-item>

        <a-form-model-item label="评论">
          <a-textarea
            :auto-size="{ minRows: 3, maxRows: 5 }"
            :disabled="lawCase.isRead"
            v-model="taskForm.comment"
          />
        </a-form-model-item>
         <a-col>
           <span style="font-size: 16px; font-weight: 700; margin-right: 10px">历史评论</span>
             <div style="width:100%;padding-top:5px">
                    <Comments :url="taskForm.id+''"/>
              </div>
         </a-col>
       </a-form-model>
       </div>
      <a-modal v-model="isShowCreateCheckItemModal" title="创建检查事项" @ok="createCheckItem">
        <a-input v-model="checkItemName" placeholder="检查事项名称" />
      </a-modal>
    </a-modal>
    </template>
    <!-- <a-button v-if="lawCase.isRead" type="primary" @click="lawCase.isRead=false">
      只读模式
    </a-button>
    <a-button v-else type="primary" @click="lawCase.isRead=true">
      编辑模式
    </a-button> -->
  </div>
    
</template>

<script>

import {getCase,createStage,sortStage,deleteStage,createTask,deleteTask,sortTask,uploadFile,saveTask} from '@/request/api'
import Comments from '@/components/Comments'
export default {
  data(){
    return {
      loading : true,
      lawCase : {
      },
      beginSort : false,
      isShowDescribe : false,
      isShowCreateStageModal : false,
      stageName : "",
      tasksGroup : [],
      isShowCreateTaskModal : false,
      curStageIndex : -1,
      taskName : "",
      isShowUpdateTaskModeal : false,
      uploading : false, 
      taskShare:'',
      taskForm : {
        id : "",
        name : "",
        describe : "",
        files : [],
        checkItems : [],
        comment: ""
      },
      isShowCreateCheckItemModal : false,
      checkItemName : "",
      curTaskIndex : -1,
      customStyle:'background: #f7f7f7;border:0px;border-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden',
      createStageLoadding:false,
      createTaskLoadding:false
      
    }
  },
  components:{
      Comments 
  },
  created(){
    this.id =  this.$route.params.id
  },
  mounted(){
    this.loadCase()
    // this.$dragging.$on('dragged', (e) => {
    //   console.log(e)
    // })
    this.$dragging.$on('dragend', (res) => {
      let group = res.group
      if(group.match(/task\w/)){
        let i = Number(group.substr(4,1))
        let params = this.lawCase.stages[i].tasks.map(t => { return { id : t.id }} )

        // 判断是否和上次一样
        if(this.params !== undefined){
          if(this.params.length == params.length){
            let f = true
            for(let i=0; i<this.params.length ;i++){
              if(this.params[i].id != params[i].id){
                f = false;
                break;
              }
            }
            if(f){
              console.log("本次数据和上次一样，不调用接口")
              return
            }
          }
        }
        this.params = params
        
        
        sortTask(params).then(()=>{
          this.$message.success("调整顺序成功")
          this.loadCase()
        }).catch(()=>{})
      }
    })
  },
  methods:{
    /** 加载案件信息 */
    loadCase(){
      getCase(this.id).then(data => {
          let lawCase = data.caseInfo
          lawCase.stages = data.stageInfo

          let tasksGroup = []
          for(let i=0;i < lawCase.stages.length; i++){
            tasksGroup.push([])
          }
          Object.assign(this,{
            tasksGroup,
            lawCase,
            loading: false
          })
      }).catch(()=>{})
    },
    change(e,i){
      let target = e.target
      if(target.checked){
        this.tasksGroup[i].push(target.value)
      }else{
        this.tasksGroup[i].splice(this.tasksGroup[i].indexOf(target.value),1)
      }
      console.log(this.tasksGroup[i])
    },
    mouseenter(){
      console.log("1")
    },
    mouseleave(){
      console.log("2")
    },
    /** 创建任务阶段  */
    createStage(){
      // 阶段名称不能为空
      this.createStageLoadding  = true
      if( !this.stageName){
        this.$message.error("阶段名称不能为空")
        this.createStageLoadding = false
        return 
      }

      createStage(this.id, {name: this.stageName}).then(() => {
        this.$message.success("创建成功")
        this.createStageLoadding = false
        this.loadCase()
        this.cancelCreateStage()
      }).catch(()=>{  this.createStageLoadding = false})
    },
    /** 完成任务阶段排序 */
    finshSort(){
      let params = this.lawCase.stages.map(e => {
          return {
            id:e.id
          }
      })
      sortStage(params).then(() => {
        this.$message.success("调整顺序成功")
        this.beginSort = false
        this.loadCase()
      }).catch(()=>{})
    },
    /** 取消任务创建 */
    cancelCreateStage(){
      this.stageName = ""
      this.isShowCreateStageModal = false
    },
    /** 显示删除任务阶段对话框 ok=> 删除阶段 */
    showDeleteStageConfirm(id,name){
      this.$confirm({
        title: '确定要删除阶段 "' + name +'" 吗？',
        content: '删除后将无法恢复',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk :()=>{
          deleteStage(id).then(() => {
            this.$message.success("删除成功")
            this.loadCase()
          }).catch(()=>{})
        },
        onCancel() {
        },
      });
    },

    showDeleteTaskItemConfirm(i){
      if(this.tasksGroup[i] && this.tasksGroup[i].length > 0){
        this.$confirm({
          title: '确定要删除被勾选的这' + this.tasksGroup[i].length +'任务吗？',
          content: '删除后将无法恢复',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk :() => {
             let params = this.tasksGroup[i].map(e => e).join()
            deleteTask(params).then(()=>{
              this.tasksGroup[i] = []
              this.$message.success("删除成功")
              this.loadCase()
            }).catch(()=>{
            })  
          },
          onCancel() {
          },
        })
      }else{
        this.$message.warning("您未选择任何事项")
      }
    },
    /** 显示创建任务事项对话框 */
    showCreateTaskItemModel(i){
      this.curStageIndex = i
      this.stageId = this.lawCase.stages[i].id
      this.isShowCreateTaskModal = true
    },
    /** 创建任务事项 */
    createTask(){
      this.createTaskLoadding = true
      if(!this.stageId){
        console.error("系统异常")
        this.$message.error("系统异常")
        this.createTaskLoadding =false
        return
      }
      if(this.taskName.length == 0){
        this.$message.error("任务名称不能为空")
        this.createTaskLoadding =false
        return 
      }

      createTask(this.stageId,{name : this.taskName}).then(()=>{
        this.$message.success("任务创建成功")
        this.createTaskLoadding =false
        this.cancelCreateTask()
        this.loadCase()
      }).catch(()=>{  this.createTaskLoadding =false     }) 
    },
    cancelCreateTask(){
      this.taskName = ""
      this.curStageIndex = -1
      this.isShowCreateTaskModal = false
    },

    showCreateCheckItemModal(){
      if(this.curStageIndex < 0 && this.curTaskIndex < 0){
        console.error("系统异常")
        return
      }
      this.isShowCreateCheckItemModal = true
    },
    createCheckItem(){
      if(this.curStageIndex < 0 && this.curTaskIndex < 0){
        console.error("系统异常")
        return
      }
      this.taskForm.checkItems.push({
         name : this.checkItemName,
         id : null,
         isDone : false
      })
      this.isShowCreateCheckItemModal = false
      this.checkItemName = ""
      this.$message.success("创建成功")
    },
    showUpdateTaskItemModel(i,j){
      this.curStageIndex = i
      this.curTaskIndex = j
      this.isShowUpdateTaskModeal = true

      let task = this.lawCase.stages[i].tasks[j]
      this.taskForm = {
        id : task.id,
        name : task.name,
        describe : task.describe,
        files : JSON.parse(JSON.stringify(task.files)),
        checkItems: JSON.parse(JSON.stringify(task.checkItems)),
        comment : task.comment,
      }
    },
    updateTask(){
      // this.lawCase.stages[this.curStageIndex].tasks[this.curTaskIndex] = {
      //   name : this.taskForm.name,
      //   describe : this.taskForm.describe,
      //   files : [...this.taskForm.files],
      //   checkItems: JSON.parse(JSON.stringify(this.taskForm.checkItems)),
      //   comment : this.taskForm.comment,
      // }
      let id = this.taskForm.id
      let params = {
        name : this.taskForm.name,
        describe : this.taskForm.describe,
        files : this.taskForm.files,
        comment : this.taskForm.comment,
        checkItems : this.taskForm.checkItems,
      }
      console.log(JSON.stringify(params))
      saveTask(this.id,id,params).then(()=>{
        this.$message.success("保存成功")
        this.cancelUpdateTask()
        this.loadCase()
      }).catch(()=>{})
    },
    cancelUpdateTask(){
      this.curTaskIndex = -1
      this.curStageIndex = -1
      this.taskForm = {}
      this.isShowUpdateTaskModeal = false
    },
    customRequest(e){
      this.uploading = true
      let file = e.file
      let fileName = file.name
      console.log(file)
      let formData = new FormData()
      formData.append('file',file)

      uploadFile(this.id,formData).then(data =>{
        this.taskForm.files.push({
          id: data,
          fileName : fileName
        })
        this.uploading = false
        this.$message.success('上传成功')
      }).catch(()=>{this.uploading = false})
    },
    beforeUpload(file){
      this.taskForm.files.push(file)
      return true
    },
    fileRemove(file){
      this.taskForm.files.splice(this.taskForm.files.indexOf(file),1)
      return true
    },
    uploadChange(e){
      console.log(e)
    },
    gotoPdfOCR(did){
      const pdfOCR = this.$router.resolve("/case/" + this.id + "/pdfOCR/" + did);
      window.open(pdfOCR.href, "_blank");
    },
    /** 删除文件 */
    delFile(id){
      this.taskForm.files = this.taskForm.files.filter(item=>item.id!=id)
    },
    share(id){
      //分享
       window.open("/workflow/request/CreateRequestForward.jsp?workflowid=28532&case_id="+this.id+"&task_id="+id, "_blank")
        // window.open("/workflow/request/CreateRequestForward.jsp?workflowid=6522&case_id="+this.id+"&task_id="+id, "_blank")
    }
  },
  computed:{
    updateTaskModealTitle(){
      return this.curStageIndex > -1 ? (this.curStageIndex + 1) + "、 "+ this.lawCase.stages[this.curStageIndex].name : '任务事项'
    },
    taskFormCheckItemsIsDone(){
      return this.taskForm.checkItems.filter(c => c.isDone).length
    },
    lawCaseDescribe(){
      return this.lawCase.describe ? this.lawCase.describe.substr(0,150) : ""
    },

    // stageDraggin(){
    //   return (stage) => {
    //     console.log(this.beginSort ? { item: stage, list: this.lawCase.stages, group: 'stage' } : null)
    //     return this.beginSort ? { item: stage, list: this.lawCase.stages, group: 'stage' } : null
    //   }
    // }
  }
}
</script>

<style lang="stylus" scoped>
.container
    background #fff 
    min-height 500px
    width 100%
    position: relative;
    .loading
      position absolute
      top 40%
      left 50%
      transform translate(-50%,-50%)
</style>